/*
 * console.c
 *
 * Created: 19/01/2014 23:39:26
 *  Author: usuario
 */ 

#include <asf.h>
#include <rtos.h>

#include "console.h"


xSemaphoreHandle xSemaphore_ConsoleTX;
xSemaphoreHandle xSemaphore_ConsoleRX;

void CONSOLE_setup ( void )
{
	const usart_serial_options_t uart_serial_options = {
		.baudrate   = CONSOLE_SPEED,
		.paritytype = CONSOLE_PARITY
	};
	
	sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
	stdio_serial_init(CONSOLE_UART, &uart_serial_options);
	
	xSemaphore_ConsoleTX = xSemaphoreCreateMutex();
	configASSERT(xSemaphore_ConsoleTX);
	xSemaphore_ConsoleRX = xSemaphoreCreateMutex();
	configASSERT(xSemaphore_ConsoleRX);
}

void CONSOLE_write(char *buffer)
{
	uint8_t	i=0;
	portTickType xNextPollingTime;
	
	xSemaphoreTake(xSemaphore_ConsoleTX, CONSOLE_POLLING_TX_TIME);
	xNextPollingTime = xTaskGetTickCount();
	while (buffer[i]!=0)
	{
		while ( uart_is_tx_ready(CONSOLE_UART) == 0 )
		{
			vTaskDelayUntil( &xNextPollingTime, CONSOLE_POLLING_TX_TIME );
		}
		uart_write(CONSOLE_UART,buffer[i]);
		i++;
	}
	xSemaphoreGive(xSemaphore_ConsoleTX);
}

void CONSOLE_read(uint8_t *c)
{
	portTickType xNextPollingTime;
	
	xSemaphoreTake(xSemaphore_ConsoleRX, CONSOLE_POLLING_RX_TIME);
	xNextPollingTime = xTaskGetTickCount();
	while ( uart_is_rx_ready(CONSOLE_UART) == 0 )
	{
		vTaskDelayUntil( &xNextPollingTime, CONSOLE_POLLING_RX_TIME );
	}
	uart_read(CONSOLE_UART,c);
	xSemaphoreGive(xSemaphore_ConsoleRX);
}
